# -*- coding:utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _

import datetime
#from dateutil.relativedelta import relativedelta

class Contract(models.Model):

    _inherit = 'hr.contract'

    tax_deduction = fields.Monetary('Tax Deduction', digits=(16, 2), help="Employee's monthly tax deduction")

class HrEmployee(models.Model):
    _inherit = 'hr.employee'

    @api.multi
    def accumulate(self, payslip,codes, sign=1):
        codes = isinstance(codes, list) and codes or [codes]
        
        date = payslip.date_from
        year_first_date = datetime.date(date.year, 1, 1)
        date_from = date
        
        old_slip_ids = self.slip_ids.filtered(
            lambda item: ( item.date_from >= year_first_date
                     ) and item.date_from < date_from )
        
        slip_lines = old_slip_ids.mapped('line_ids').filtered(
            lambda item: item.category_id.code in codes)
        
        ret = sign * sum(slip_lines.mapped('total'))
        print (codes, ret)
        return ret

class HrPayslipLine(models.Model):
    _inherit = 'hr.payslip.line'
    _order = 'contract_id, appears_on_payslip desc, sequence'

class ResCompany(models.Model):
    _inherit = "res.company"

    @api.model
    def create(self, vals):
        company = super(ResCompany, self).create(vals)
        
        # create salary rule of this company
        company._copy_hr_payroll()
        return company

    @api.multi
    def _copy_hr_payroll(self):
        self._copy_hr_contribution_register()
        self._copy_hr_salary_rule_category()
        self._copy_hr_salary_rule()
        self._copy_hr_rule_input()
        self._copy_hr_payroll_structure()

    @api.multi
    def _copy_hr_contribution_register(self):
        main_company = self.env.ref('base.main_company')
        hr_obj = self.env['hr.contribution.register']
        hr_obj = hr_obj.search([('company_id','=', main_company.id)])

        vals = [{
            'name':item.name,
            'partner_id': item.partner_id.id,
            'company_id': self.id
        } for item in hr_obj ]

        return hr_obj.create(vals)

    @api.multi
    def _copy_hr_salary_rule_category(self):
        main_company = self.env.ref('base.main_company')
        hr_obj = self.env['hr.salary.rule.category']
        hr_obj = hr_obj.search([('company_id','=', main_company.id)])

        vals = [{
            'name':item.name,
            'code': item.code,
            'company_id': self.id
        } for item in hr_obj ]

        new_hr_obj = hr_obj.create(vals)

        for item in new_hr_obj:
            old = hr_obj.filtered(lambda old: old.code == item.code )
            if not old.parent_id:
                continue

            new = new_hr_obj.filtered(lambda new: new.code == old.parent_id.code )
            item.parent_id = new.id

        return new_hr_obj

    @api.multi
    def _copy_hr_salary_rule(self):
        main_company = self.env.ref('base.main_company')

        hr_obj = self.env['hr.salary.rule']
        hr_obj = hr_obj.search([('company_id','=', main_company.id)])

        def _fn_m2o_category_id(item):
            return self.env['hr.salary.rule.category'].search(
                [('company_id','=', self.id),
                 ('code','=',item.category_id.code)
                ],limit=1 ).id

        def _fn_m2o_register_id(item):
            if not item.register_id:
                return False

            return self.env['hr.contribution.register'].search(
                [('company_id','=', self.id),
                 ('name','=',item.register_id.name)
                ],limit=1 ).id

        vals = [{
            'name':item.name,
            'code': item.code,
            'sequence': item.sequence,
            'category_id': _fn_m2o_category_id(item),
            'appears_on_payslip': item.appears_on_payslip,
            'company_id': self.id,
            'quantity': item.quantity,
            'condition_select': item.condition_select,
            #'condition_range': item.condition_range,
            'amount_select': item.amount_select,
            #'amount_fix': item.amount_fix,
            #'amount_percentage': item.amount_percentage,
            'amount_python_compute': item.amount_python_compute,
            #'amount_percentage_base': item.amount_percentage_base,
            'register_id': _fn_m2o_register_id(item),
        } for item in hr_obj ]

        new_hr_obj = hr_obj.create(vals)

        for item in new_hr_obj:
            old = hr_obj.filtered(lambda old: old.code == item.code )
            if not old.parent_rule_id:
                continue

            new = new_hr_obj.filtered(lambda new: new.code == old.parent_rule_id.code )
            item.parent_rule_id = new.id

        return new_hr_obj

    @api.multi
    def _copy_hr_rule_input(self):
        main_company = self.env.ref('base.main_company')
        hr_obj = self.env['hr.rule.input']
        hr_obj = hr_obj.search([('input_id.company_id','=', main_company.id)])

        def _fn_m2o_input_id(item):
            return self.env['hr.salary.rule'].search(
                [('company_id','=', self.id),
                 ('code','=',item.input_id.code)
                ],limit=1 ).id

        vals = [{
            'name':item.name,
            'code': item.code,
            'input_id': _fn_m2o_input_id(item),
        } for item in hr_obj ]

        new_hr_obj = hr_obj.create(vals)

        return new_hr_obj

    @api.multi
    def _copy_hr_payroll_structure(self):
        main_company = self.env.ref('base.main_company')
        hr_obj = self.env['hr.payroll.structure']
        hr_obj = hr_obj.search([('company_id','=', main_company.id)])
        
        def _fn_m2m_rule_ids(item):
            m2m = self.env['hr.salary.rule'].search(
                [('company_id','=', self.id),
                 ('code','in',item.rule_ids.mapped('code') )
                ])
            return [(6, 0, m2m.ids)]
        

        vals = [{
            'name':item.name,
            'code': item.code,
            'rule_ids': _fn_m2m_rule_ids(item),
            'company_id': self.id,
        } for item in hr_obj ]

        new_hr_obj = hr_obj.create(vals)

        for item in new_hr_obj:
            old = hr_obj.filtered(lambda old: old.code == item.code )
            if not old.parent_id:
                continue

            new = new_hr_obj.filtered(lambda new: new.code == old.parent_id.code )
            item.parent_id = new.id

        return new_hr_obj

